// 这里可以使用Pinia或Vuex进行状态管理
// 示例为一个空的store文件，后续可以根据需要添加内容

import { defineStore } from "pinia";
import { createPinia } from "pinia";
import { getMerchantStores } from "@/api/index";
import { ElMessage } from "element-plus"; // 导入 ElMessage

// 创建主题状态管理
export const useThemeStore = defineStore("theme", {
  state: () => ({
    isDark: localStorage.getItem("customer-theme") === "dark",
    currentModule: "customer" as "customer" | "merchant" | "admin",
  }),

  actions: {
    // 切换顾客端主题
    toggleCustomerTheme() {
      this.isDark = !this.isDark;
      this.currentModule = "customer";
      
      // 添加一个微小的延迟以确保状态更新完成
      setTimeout(() => {
        this.applyCustomerTheme();
      }, 10);
    },

    // 应用顾客端主题
    applyCustomerTheme() {
      // 清除所有主题类
      document.documentElement.classList.remove("dark-theme", "merchant-theme", "admin-theme");
      document.body.classList.remove("merchant-layout-body", "admin-layout-body");
      
      if (this.isDark) {
        document.documentElement.classList.add("dark-theme");
        document.body.classList.add("customer-dark-theme");
        localStorage.setItem("customer-theme", "dark");
      } else {
        document.body.classList.remove("customer-dark-theme");
        document.body.classList.add("customer-light-theme");
        localStorage.setItem("customer-theme", "light");
      }
      
      // 重置CSS变量为顾客端默认值
      this.resetToCustomerVariables();
    },

    // 应用商家端主题
    applyMerchantTheme() {
      // 清除所有主题类
      document.documentElement.classList.remove("dark-theme");
      document.body.classList.remove("customer-dark-theme", "customer-light-theme", "admin-layout-body");
      
      document.documentElement.classList.add("merchant-theme");
      document.body.classList.add("merchant-layout-body");
      this.currentModule = "merchant";
    },

    // 应用管理员主题
    applyAdminTheme() {
      // 清除所有主题类
      document.documentElement.classList.remove("dark-theme", "merchant-theme");
      document.body.classList.remove("customer-dark-theme", "customer-light-theme", "merchant-layout-body");
      
      document.documentElement.classList.add("admin-theme");
      document.body.classList.add("admin-layout-body");
      this.currentModule = "admin";
    },

    // 重置为顾客端CSS变量
    resetToCustomerVariables() {
      // 不再设置全局CSS变量，而是依赖body类名来控制样式
      // 这样避免影响商家端的CSS变量
      console.log('顾客端主题已应用，使用body类名控制样式');
    },

    // 初始化主题（根据当前路由）
    initTheme(route?: string) {
      if (route?.includes('/merchant')) {
        this.applyMerchantTheme();
      } else if (route?.includes('/admin')) {
        this.applyAdminTheme();
      } else {
        this.applyCustomerTheme();
      }
    },

    // 兼容性方法（保持原有API）
    toggleTheme() {
      this.toggleCustomerTheme();
    },

    applyTheme() {
      this.applyCustomerTheme();
    },
  },
});

// 创建商家店铺状态管理
export const useMerchantStore = defineStore("merchant", {
  state: () => ({
    currentStoreId: localStorage.getItem("currentStoreId") || "",
    stores: [] as any[],
    storeInfo: {} as any,
    loading: false,
    suppressStatusNotification: true,
  }),

  getters: {
    hasStores: (state) => state.stores.length > 0,
    currentStore: (state) => state.storeInfo,
  },

  actions: {
    // 设置当前选中的店铺
    setCurrentStore(storeId: string) {
      console.log("设置当前店铺ID:", storeId);
      this.currentStoreId = storeId;
      localStorage.setItem("currentStoreId", storeId);

      // 更新当前店铺信息
      const store = this.stores.find((s) => s.id === storeId);
      if (store) {
        console.log("找到对应店铺信息:", store);
        this.storeInfo = { ...store };
      } else {
        console.log("未找到对应店铺信息");
      }
    },

    // 获取商家所有店铺
    async fetchStores(suppressNotification = false) {
      console.log("开始获取店铺列表");
      this.loading = true;
      try {
        const res = await getMerchantStores();
        console.log("获取店铺列表响应:", res);
        const list = res.data?.data || res.data;
        this.stores = Array.isArray(list) ? list : list?.list || [];
        console.log("解析后的店铺列表:", this.stores);

        // 如果有店铺但没有选中的店铺，选择第一个
        if (this.stores.length > 0) {
          if (
            !this.currentStoreId ||
            !this.stores.find((s) => s.id === this.currentStoreId)
          ) {
            console.log("没有当前选中店铺或找不到匹配的店铺，选择第一个店铺");
            this.currentStoreId = this.stores[0].id;
            localStorage.setItem("currentStoreId", this.stores[0].id);
            this.storeInfo = { ...this.stores[0] };
          } else {
            // 更新当前店铺信息
            console.log("更新当前店铺信息，当前ID:", this.currentStoreId);
            const store = this.stores.find((s) => s.id === this.currentStoreId);
            if (store) {
              console.log("找到对应店铺信息:", store);
              this.storeInfo = { ...store };
            } else {
              console.log("未找到对应店铺信息");
            }
          }
        } else {
          console.log("没有店铺数据");
          this.currentStoreId = "";
          this.storeInfo = {};
        }
      } catch (error) {
        console.error("获取店铺列表失败", error);
      } finally {
        this.loading = false;
      }
    },

    // 更新店铺状态
    updateStoreStatus(status: string, suppressNotification = false) {
      console.log("更新店铺状态:", status, "抑制通知:", suppressNotification);
      if (this.storeInfo) {
        // 保存旧状态用于日志
        const oldStatus = this.storeInfo.status;

        // 更新状态
        this.storeInfo.status = status;
        console.log(`店铺状态从 ${oldStatus} 更新为 ${status}`);

        // 同时更新stores数组中的对应店铺状态
        const storeIndex = this.stores.findIndex(
          (s) => s.id === this.currentStoreId
        );
        if (storeIndex !== -1) {
          console.log("更新stores数组中的店铺状态");
          this.stores[storeIndex].status = status;
        } else {
          console.log("未找到stores数组中对应的店铺");
        }

        // 如果不抑制通知，则显示成功消息
        if (!suppressNotification) {
          ElMessage.success("店铺状态更新成功");
        }
      } else {
        console.log("没有当前店铺信息，无法更新状态");
      }
    },
  },
});

// 创建pinia实例
const pinia = createPinia();

export default pinia;
